package org.unique.plugin.mongo;

import java.net.UnknownHostException;
import java.util.List;
import java.util.Properties;

import org.unique.common.tools.CollectionUtil;
import org.unique.common.tools.PropUtil;

import com.mongodb.DB;
import com.mongodb.MongoClient;
import com.mongodb.ServerAddress;

/**
 * mongo连接管理
 *@author:rex
 *@date:2014年8月12日
 *@version:1.0
 */
public final class MongoManager {

	//mongoclient实例
	private static MongoClient mongoClient = null;
	
	static {
		Properties prop = PropUtil.getProperty("db.properties");
		if(null != prop && prop.containsKey("mongo.ips")){
			try {
				// 创建多个mongo共享服务，分布式时
	            String[] ips = prop.getProperty("mongo.ips").split(",");
	            List<ServerAddress> seeds = CollectionUtil.newArrayList();
	            for (String ip : ips) {
	            	seeds.add(new ServerAddress(ip.split(":")[0], Integer.valueOf(ip.split(":")[1])));
	            }
	            if(seeds.size() > 0){
	            	mongoClient = new MongoClient(seeds);
	            }
			} catch (UnknownHostException e) {
				e.printStackTrace();
			}
		}
	}

	private MongoManager() {
	}

	/**
	 * 获取db
	 * @param dbname
	 * @return
	 */
	public static DB getDB(String dbname) {
		if (null != mongoClient) {
			return mongoClient.getDB(dbname);
		}
		return null;
	}
	
	/**
	 * 获取db
	 * @param dbname
	 * @return
	 */
	public static DB getBlogDB() {
		if (null != mongoClient) {
			return mongoClient.getDB("unique_blog");
		} else{
			throw new RuntimeException("the blog db is null");
		}
	}
	
}
